<?php
declare (strict_types=1);

namespace app\common\model;

class Level extends Base
{
    protected $name = 'user_level';

    /**
     * 团队级别升级
     * @param $uid
     * @return array
     */
    public static function upgrade($uid): array
    {
        try {
            Relation::with('user')->where('new_uid', $uid)
                ->field('id,uid,algebra')->order('algebra', 'asc')->select()
                ->each(function ($item){
                    if($item->user->is_active == 2){
                        $level_id = self::getLevelId($item->user);
                        if($level_id > $item->user->level_id){
                            $item->user->level_id = $level_id;
                            $item->user->save();
                        }
                    }
                });
            return ['code' => 1, 'msg' => 'success'];
        } catch (\Exception $e) {
            Logs::exception($e);
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function getLevelId($user)
    {
        try{
            if($user->level_id >= 5) return 5;
            return self::recursion($user);
        }catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    private static function recursion($user, $level_id = 5, $children = null)
    {
        try{
            if($level_id <= 0) return 0;
            $level = self::find($level_id);
            if($level_id == 1 && $user->zt_count >= $level->zt_count){
                return 1;
            }
            $line = 0;

            !$children && $children = User::where('parent_id', $user->id)->column('id');
            foreach ($children as $child){
                $new_uid = Relation::where('uid', $child)->column('new_uid');
                array_push($new_uid, $child);

                $child_count = User::where('level_id', '>=', $level_id - 1)->whereIn('id', $new_uid)->count();
                $child_count >= $level->n && $line ++;

                if($line >= $level->m){
                    return $level_id;
                }
            }

            return self::recursion($user, --$level_id, $children);
        }catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

}